<template>
  <div class="boss">
    <div class="login">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userpwd">
          <el-input
            type="password"
            v-model="ruleForm.userpwd"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm()">提交</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import userModel from "../../model/user";
export default {
  data() {
    return {
      ruleForm: {
        //表示是表单中的数据
        username: "",
        userpwd: "",
      },
      rules: {
        //表示表单中数据验证的规则
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          {
            pattern: /^[0-9a-z]{3,10}$/i,
            message: "长度在 3 到 10 个字符只能数字字母组成",
            trigger: "blur",
          },
        ],

        userpwd: [{ required: true, message: "密码不能为空", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        //对表单进行验证
        if (valid) {
          //为true就是验证成功
          console.log(this.ruleForm.username + "密码" + this.ruleForm.userpwd);
          let { data } = await userModel.login({
            username: this.ruleForm.username,
            userpwd: this.ruleForm.userpwd,
          });
          if (data.code == 1) {
            //表示登录成功
            console.log(data);
            //存储token 和跳转页面
            window.localStorage.setItem("token", data.token);
            this.$router.push("/" + data.path);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      //取消
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>

<style scoped>
*{
  margin: 0;
  padding: 0;
}
body{
  background-color: skyblue;
}

.login{
  width: 500px;
  height: 300px;
  margin: 100px auto;
  
}

</style>